package com.wisdom.client.cluster.lb;

import com.wisdom.client.cluster.ClientLoadBalanceStrategy;
import com.wisdom.core.annotation.WisdomLoadBalance;
import com.wisdom.core.enums.LoadBalanceStrategy;
import com.wisdom.core.exception.RpcException;
import com.wisdom.core.provider.ServiceProvider;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: <轮询负载均衡算法>
 * @author: Leo
 * @date: 2021-08-29 16:52
 */
@WisdomLoadBalance(strategy = LoadBalanceStrategy.POLLING)
public class PollingClientLoadBalance implements ClientLoadBalanceStrategy {

    private int index;

    private static final ReentrantLock lock = new ReentrantLock();

    @Override
    public ServiceProvider getProvider(List<? extends ServiceProvider> serviceProviders) {
        try {
            boolean tryLock = lock.tryLock(100, TimeUnit.MILLISECONDS);
            if (tryLock){
                ServiceProvider serviceProvider = serviceProviders.get(index);
                index = (index +1) % serviceProviders.size();
                return serviceProvider;
            }else {
                lock.wait(100);
                return getProvider(serviceProviders);
            }
        } catch (InterruptedException e) {
            throw new RpcException(e.getMessage(),e);
        }finally {
            lock.unlock();
        }
    }
}
